<template>
  <div class="my-blogs-page">
    <!-- 顶部导航 -->
    <Navbar />
    
    <!-- 页面头部 -->
    <header class="page-header">
      <div class="header-container">
        <div class="header-left">
          <button class="btn-back" @click="goBack">
            <el-icon><ArrowLeft /></el-icon>
            返回
          </button>
          <div class="header-title-group">
            <h1 class="page-title">我的博客</h1>
            <p class="page-subtitle">管理和编辑你的所有文章</p>
          </div>
        </div>
        <div class="header-right">
          <button class="btn-refresh" @click="refreshData">
            <el-icon><Refresh /></el-icon>
            刷新
          </button>
          <button class="btn-create" @click="goToCreate">
            <el-icon><EditPen /></el-icon>
            发布新文章
          </button>
        </div>
      </div>
    </header>

    <!-- 主内容 -->
    <main class="main-wrapper">
      <div class="container">
        <!-- 统计卡片 -->
        <div class="stats-grid">
          <div class="stat-card">
            <div class="stat-icon" style="background: linear-gradient(135deg, #0EA5E9 0%, #2563EB 100%);">
              <el-icon><Document /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-value">{{ stats.blogTotal }}</div>
              <div class="stat-label">总文章数</div>
            </div>
          </div>

          <div class="stat-card">
            <div class="stat-icon" style="background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);">
              <el-icon><View /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-value">{{ totalViews }}</div>
              <div class="stat-label">总浏览量</div>
            </div>
          </div>

          <div class="stat-card">
            <div class="stat-icon" style="background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);">
              <el-icon><Star /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-value">{{ totalFavorites }}</div>
              <div class="stat-label">总收藏数</div>
            </div>
          </div>

          <div class="stat-card">
            <div class="stat-icon" style="background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%);">
              <el-icon><Star /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-value">{{ totalLikes }}</div>
              <div class="stat-label">总点赞数</div>
            </div>
          </div>
        </div>

        <!-- 加载状态 -->
        <div v-if="loading" class="loading-state">
          <el-icon class="is-loading" :size="48"><Loading /></el-icon>
          <p>加载中...</p>
        </div>

        <!-- 空状态 -->
        <div v-else-if="myBlogs.length === 0" class="empty-state">
          <el-icon :size="80"><DocumentDelete /></el-icon>
          <h3>还没有发布文章</h3>
          <p>开始写作，分享你的技术见解</p>
          <button class="btn-create-large" @click="goToCreate">
            <el-icon><EditPen /></el-icon>
            立即发布
          </button>
        </div>

        <!-- 博客列表 -->
        <div v-else class="blogs-section">
          <div class="section-header">
            <h2>文章列表</h2>
            <span class="article-count">共 {{ total }} 篇文章</span>
          </div>

          <div class="blog-list">
            <div
              v-for="blog in myBlogs"
              :key="blog.id"
              class="blog-item"
            >
              <div class="blog-content" @click="viewBlog(blog.id)">
                <div class="blog-header">
                  <h3 class="blog-title">{{ blog.title }}</h3>
                  <div class="blog-status">
                    <el-tag v-if="blog.status === 1" type="success" size="small">已发布</el-tag>
                    <el-tag v-else type="info" size="small">草稿</el-tag>
                  </div>
                </div>

                <p class="blog-summary">
                  {{ blog.summary || truncateContent(blog.content) }}
                </p>

                <div v-if="blog.tags && blog.tags.length > 0" class="blog-tags">
                  <span v-for="tag in blog.tags.slice(0, 4)" :key="tag" class="tag">
                    #{{ tag }}
                  </span>
                </div>

                <div class="blog-meta">
                  <span class="meta-item">
                    <el-icon><Calendar /></el-icon>
                    {{ formatDate(blog.publishedAt || blog.createdAt) }}
                  </span>
                  <span class="meta-item">
                    <el-icon><View /></el-icon>
                    {{ blog.viewCount || 0 }}
                  </span>
                  <span class="meta-item">
                    <el-icon><Star /></el-icon>
                    {{ blog.favoriteCount || 0 }}
                  </span>
                  <span class="meta-item">
                    <el-icon><ChatDotRound /></el-icon>
                    {{ blog.commentCount || 0 }}
                  </span>
                </div>
              </div>

              <div class="blog-actions">
                <button class="action-btn edit" @click.stop="editBlog(blog.id)">
                  <el-icon><Edit /></el-icon>
                  编辑
                </button>
                <button class="action-btn delete" @click.stop="deleteBlogConfirm(blog.id)">
                  <el-icon><Delete /></el-icon>
                  删除
                </button>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 分页固定在底部 -->
      <footer v-if="!loading && myBlogs.length > 0" class="pagination-footer">
        <div class="pagination-wrapper">
          <el-pagination
            v-model:current-page="pageIndex"
            v-model:page-size="pageSize"
            :total="total"
            :page-sizes="[10, 20, 50]"
            layout="total, sizes, prev, pager, next, jumper"
            @current-change="handlePageChange"
            @size-change="handleSizeChange"
            background
          />
        </div>
      </footer>
    </main>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  ArrowLeft,
  Refresh,
  EditPen,
  Document,
  View,
  Star,
  ChatDotRound,
  Loading,
  DocumentDelete,
  Calendar,
  Edit,
  Delete
} from '@element-plus/icons-vue'
import { getUserBlogList, deleteBlog, getUserBlogDetail, getUserBlogStats } from '../api/blog'
import Navbar from '../components/Navbar.vue'
import { normalizeTags } from '../utils/tags'

const router = useRouter()

const myBlogs = ref([])
const loading = ref(false)
const pageIndex = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 统计数据
const stats = ref({
  blogTotal: 0,
  viewCount: 0,
  likeCount: 0,
  favoriteCount: 0
})

const totalViews = computed(() => {
  return stats.value.viewCount || 0
})

const totalFavorites = computed(() => {
  return stats.value.favoriteCount || 0
})

const totalLikes = computed(() => {
  return stats.value.likeCount || 0
})

// 获取统计数据
const fetchStats = async () => {
  try {
    const res = await getUserBlogStats()
    stats.value = {
      blogTotal: res.blogTotal || 0,
      viewCount: res.viewCount || 0,
      likeCount: res.likeCount || 0,
      favoriteCount: res.favoriteCount || 0
    }
    // 更新总文章数
    total.value = res.blogTotal || 0
  } catch (error) {
    console.error('获取统计数据失败:', error)
  }
}

const fetchMyBlogs = async () => {
  loading.value = true
  try {
    const res = await getUserBlogList({
      pageIndex: pageIndex.value,
      pageSize: pageSize.value
    })

    myBlogs.value = (res.data || []).map(blog => ({
      ...blog,
      tags: normalizeTags(blog.tags)  // 使用公共工具处理标签
    }))
    
    console.log('我的博客页-第一条原始数据:', (res.data || [])[0])
    console.log('处理后第一条博客tags:', myBlogs.value[0]?.tags)
    // 如果接口返回了 total，也更新它
    if (res.total !== undefined) {
      total.value = res.total
    }
  } catch (error) {
    console.error('获取博客列表失败:', error)
  } finally {
    loading.value = false
  }
}

const handlePageChange = (page) => {
  pageIndex.value = page
  fetchMyBlogs()
}

const handleSizeChange = (size) => {
  pageSize.value = size
  pageIndex.value = 1
  fetchMyBlogs()
}

const truncateContent = (content) => {
  if (!content) return ''
  const text = content.replace(/<[^>]*>/g, '')
  const maxLength = 120
  return text.length > maxLength ? text.substring(0, maxLength) + '...' : text
}

const formatDate = (dateString) => {
  if (!dateString) return ''
  const date = new Date(dateString)
  return date.toLocaleDateString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit'
  })
}

const viewBlog = async (id) => {
  try {
    await getUserBlogDetail(id)
    router.push(`/blogs/${id}`)
  } catch (error) {
    console.error('获取博客详情失败:', error)
    ElMessage.error('无法访问该博客')
  }
}

const editBlog = (id) => {
  router.push(`/edit/${id}`)
}

const deleteBlogConfirm = async (id) => {
  try {
    await ElMessageBox.confirm(
      '确定要删除这篇文章吗？此操作不可恢复。',
      '删除确认',
      {
        confirmButtonText: '确定删除',
        cancelButtonText: '取消',
        type: 'warning',
        confirmButtonClass: 'confirm-delete'
      }
    )
    await handleDelete(id)
  } catch (error) {
    // 用户取消删除
  }
}

const handleDelete = async (id) => {
  try {
    await deleteBlog(id)
    ElMessage.success('删除成功')
    // 删除后重新获取统计数据和博客列表
    fetchStats()
    fetchMyBlogs()
  } catch (error) {
    console.error('删除失败:', error)
  }
}

// 刷新数据
const refreshData = () => {
  fetchStats()
  fetchMyBlogs()
}

const goBack = () => {
  router.back()
}

const goToCreate = () => {
  router.push('/create')
}

onMounted(() => {
  fetchStats()
  fetchMyBlogs()
})
</script>

<style scoped>
.my-blogs-page {
  min-height: 100vh;
  background: var(--bg-primary);
  display: flex;
  flex-direction: column;
}

/* 页面头部 */
.page-header {
  background: var(--bg-secondary);
  border-bottom: 1px solid var(--border-normal);
  box-shadow: var(--shadow-sm);
}

.header-container {
  max-width: 1400px;
  margin: 0 auto;
  padding: 24px 32px;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 20px;
}

.header-title-group {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.header-right {
  display: flex;
  align-items: center;
  gap: 12px;
}

.btn-back {
  display: flex;
  align-items: center;
  gap: 6px;
  padding: 8px 16px;
  border: 1.5px solid var(--border-normal);
  border-radius: 8px;
  background: var(--bg-tertiary);
  color: var(--text-secondary);
  font-size: 14px;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.2s;
}

.btn-back:hover {
  border-color: var(--primary-start);
  color: var(--primary-start);
  background: var(--bg-hover);
}

.page-title {
  font-size: 24px;
  font-weight: 800;
  background: var(--gradient-primary);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  margin: 0;
  line-height: 1;
}

.page-subtitle {
  font-size: 13px;
  color: var(--text-tertiary);
  margin: 0;
}

.btn-refresh {
  display: flex;
  align-items: center;
  gap: 6px;
  padding: 10px 16px;
  border: 1.5px solid var(--border-normal);
  border-radius: 8px;
  background: var(--bg-tertiary);
  color: var(--text-secondary);
  font-size: 14px;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.2s;
}

.btn-refresh:hover {
  border-color: var(--primary-start);
  color: var(--primary-start);
  background: var(--bg-hover);
}

.btn-create {
  display: flex;
  align-items: center;
  gap: 6px;
  padding: 10px 20px;
  border: none;
  border-radius: 8px;
  background: var(--gradient-primary);
  color: var(--bg-primary);
  font-size: 14px;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s;
  box-shadow: var(--shadow-glow);
}

.btn-create:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 16px rgba(0, 212, 255, 0.5);
}

/* 主内容 */
.main-wrapper {
  flex: 1;
  max-width: 1400px;
  margin: 0 auto;
  padding: 40px 32px 0;
  width: 100%;
  display: flex;
  flex-direction: column;
}

/* 统计卡片 */
.stats-grid {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 20px;
  margin-bottom: 32px;
}

.stat-card {
  background: var(--bg-card);
  border-radius: 12px;
  padding: 20px;
  display: flex;
  align-items: center;
  gap: 16px;
  box-shadow: var(--shadow-sm);
  border: 1px solid var(--border-light);
  transition: all 0.3s;
}

.stat-card:hover {
  transform: translateY(-2px);
  box-shadow: var(--shadow-md);
  border-color: var(--border-normal);
}

.stat-icon {
  width: 48px;
  height: 48px;
  border-radius: 10px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  font-size: 22px;
  flex-shrink: 0;
}

.stat-info {
  flex: 1;
}

.stat-value {
  font-size: 28px;
  font-weight: 800;
  color: var(--text-bright);
  line-height: 1;
  margin-bottom: 4px;
}

.stat-label {
  font-size: 12px;
  color: var(--text-tertiary);
  font-weight: 500;
}

/* 空状态 */
.empty-state {
  text-align: center;
  padding: 100px 20px;
  background: var(--bg-card);
  border-radius: 12px;
  box-shadow: var(--shadow-sm);
  border: 1px solid var(--border-light);
}

.empty-state .el-icon {
  color: var(--text-tertiary);
  margin-bottom: 24px;
  opacity: 0.5;
}

.empty-state h3 {
  font-size: 22px;
  font-weight: 700;
  color: var(--text-bright);
  margin: 0 0 12px 0;
}

.empty-state p {
  font-size: 15px;
  color: var(--text-secondary);
  margin: 0 0 32px 0;
}

.btn-create-large {
  display: inline-flex;
  align-items: center;
  gap: 8px;
  padding: 14px 32px;
  border: none;
  border-radius: 10px;
  background: var(--gradient-primary);
  color: var(--bg-primary);
  font-size: 16px;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s;
  box-shadow: var(--shadow-glow);
}

.btn-create-large:hover {
  transform: translateY(-2px);
  box-shadow: 0 6px 20px rgba(0, 212, 255, 0.5);
}

/* 加载状态 */
.loading-state {
  text-align: center;
  padding: 100px 20px;
  color: var(--text-tertiary);
}

.loading-state .el-icon {
  color: var(--primary-start);
}

.loading-state p {
  margin-top: 16px;
  font-size: 16px;
  color: var(--text-secondary);
}

/* 博客列表 */
.blogs-section {
  background: var(--bg-card);
  border-radius: 12px;
  padding: 28px;
  box-shadow: var(--shadow-sm);
  border: 1px solid var(--border-light);
}

.section-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 20px;
  padding-bottom: 16px;
  border-bottom: 1px solid var(--border-normal);
}

.section-header h2 {
  font-size: 18px;
  font-weight: 700;
  color: var(--text-bright);
  margin: 0;
}

.article-count {
  font-size: 13px;
  color: var(--text-tertiary);
  font-weight: 500;
}

.blog-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.blog-item {
  display: flex;
  gap: 16px;
  padding: 20px;
  border: 1px solid var(--border-light);
  border-radius: 8px;
  transition: all 0.2s;
  background: var(--bg-tertiary);
}

.blog-item:hover {
  border-color: var(--primary-start);
  background: var(--bg-hover);
  transform: translateX(2px);
}

.blog-content {
  flex: 1;
  cursor: pointer;
  min-width: 0;
}

.blog-header {
  display: flex;
  align-items: flex-start;
  justify-content: space-between;
  gap: 16px;
  margin-bottom: 10px;
}

.blog-title {
  font-size: 17px;
  font-weight: 700;
  color: var(--text-bright);
  margin: 0;
  line-height: 1.4;
  transition: color 0.2s;
}

.blog-item:hover .blog-title {
  color: var(--primary-start);
}

.blog-summary {
  font-size: 14px;
  color: var(--text-secondary);
  line-height: 1.6;
  margin: 0 0 10px 0;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.blog-tags {
  display: flex;
  gap: 6px;
  flex-wrap: wrap;
  margin-bottom: 12px;
}

.tag {
  font-size: 12px;
  color: var(--primary-start);
  background: rgba(14, 165, 233, 0.15);
  padding: 4px 10px;
  border-radius: 4px;
  font-weight: 500;
}

.blog-meta {
  display: flex;
  gap: 16px;
  flex-wrap: wrap;
}

.meta-item {
  display: flex;
  align-items: center;
  gap: 4px;
  font-size: 12px;
  color: var(--text-tertiary);
  font-weight: 500;
}

.meta-item .el-icon {
  font-size: 14px;
  color: var(--text-tertiary);
}

.blog-actions {
  display: flex;
  flex-direction: column;
  gap: 8px;
  flex-shrink: 0;
}

.action-btn {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 6px;
  padding: 8px 14px;
  border: none;
  border-radius: 6px;
  font-size: 13px;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.2s;
  white-space: nowrap;
}

.action-btn.edit {
  background: rgba(14, 165, 233, 0.15);
  color: var(--primary-start);
}

.action-btn.edit:hover {
  background: var(--primary-start);
  color: var(--bg-primary);
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(14, 165, 233, 0.4);
}

.action-btn.delete {
  background: rgba(239, 68, 68, 0.15);
  color: #ef4444;
}

.action-btn.delete:hover {
  background: #ef4444;
  color: white;
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(239, 68, 68, 0.4);
}

/* 分页固定在底部 */
.pagination-footer {
  margin-top: auto;
  background: var(--bg-secondary);
  border-top: 1px solid var(--border-normal);
  padding: 16px 0;
}

.pagination-wrapper {
  max-width: 1400px;
  margin: 0 auto;
  padding: 0 32px;
  display: flex;
  justify-content: center;
}

:deep(.el-pagination) {
  gap: 6px;
  background: transparent !important;
}

:deep(.el-pagination .el-pagination__total) {
  color: var(--text-secondary);
  font-weight: 500;
  font-size: 13px;
}

:deep(.el-pagination .el-pagination__sizes) {
  background: transparent !important;
}

:deep(.el-pagination .el-select) {
  background: transparent !important;
}

:deep(.el-pagination .el-select .el-input__wrapper) {
  background: var(--bg-tertiary) !important;
  box-shadow: none !important;
  border: 1px solid var(--border-normal);
  transition: all 0.2s;
  height: 28px;
}

:deep(.el-pagination .el-select .el-input__wrapper:hover) {
  background: var(--bg-hover) !important;
  border-color: var(--primary-start);
}

:deep(.el-pagination .el-select .el-input__wrapper.is-focus) {
  background: var(--bg-hover) !important;
  border-color: var(--primary-start);
  box-shadow: 0 0 0 2px rgba(14, 165, 233, 0.1) !important;
}

:deep(.el-pagination .el-select .el-input__inner) {
  color: var(--text-bright);
}

:deep(.el-pagination button),
:deep(.el-pagination .el-pager li) {
  background: var(--bg-tertiary) !important;
  color: var(--text-secondary);
  border: 1px solid var(--border-normal);
  border-radius: 4px;
  min-width: 28px;
  height: 28px;
  line-height: 28px;
  font-size: 13px;
  transition: all 0.2s;
}

:deep(.el-pagination button:hover),
:deep(.el-pagination .el-pager li:hover) {
  color: var(--primary-start);
  border-color: var(--primary-start);
  background: rgba(14, 165, 233, 0.1) !important;
}

:deep(.el-pagination button:disabled),
:deep(.el-pagination button:disabled:hover) {
  background: var(--bg-secondary) !important;
  color: var(--text-tertiary);
  border-color: var(--border-light);
  cursor: not-allowed;
  opacity: 0.5;
}

:deep(.el-pagination .el-pager li.is-active) {
  background: var(--primary-start) !important;
  color: #fff;
  border-color: var(--primary-start);
  font-weight: 600;
  box-shadow: 0 2px 8px rgba(14, 165, 233, 0.3);
}

:deep(.el-pagination .el-pager li.is-active:hover) {
  background: var(--primary-light) !important;
}

:deep(.el-pagination .el-pagination__jump) {
  color: var(--text-secondary);
  margin-left: 8px;
  font-size: 13px;
}

:deep(.el-pagination .el-input__wrapper) {
  background: var(--bg-tertiary) !important;
  box-shadow: none !important;
  border: 1px solid var(--border-normal);
  padding: 2px 6px;
  height: 28px;
  transition: all 0.2s;
}

:deep(.el-pagination .el-input__wrapper:hover) {
  background: var(--bg-hover) !important;
  border-color: var(--primary-start);
}

:deep(.el-pagination .el-input__wrapper.is-focus) {
  background: var(--bg-hover) !important;
  border-color: var(--primary-start);
  box-shadow: 0 0 0 2px rgba(14, 165, 233, 0.1) !important;
}

:deep(.el-pagination .el-input__inner) {
  background: transparent !important;
  color: var(--text-bright);
  border: none;
  text-align: center;
  height: 24px;
  line-height: 24px;
}

:deep(.el-pagination .el-input__inner:focus) {
  border: none;
  box-shadow: none;
}

/* 响应式 */
@media (max-width: 1200px) {
  .stats-grid {
    grid-template-columns: repeat(2, 1fr);
  }
}

@media (max-width: 768px) {
  .navbar-container {
    padding: 12px 16px;
    flex-direction: column;
    align-items: stretch;
    gap: 12px;
  }

  .navbar-left,
  .navbar-right {
    justify-content: space-between;
  }

  .main-wrapper {
    padding: 24px 16px;
  }

  .stats-grid {
    grid-template-columns: 1fr;
  }

  .blogs-section {
    padding: 20px;
  }

  .blog-item {
    flex-direction: column;
  }

  .blog-actions {
    flex-direction: row;
    justify-content: flex-end;
  }

  .action-btn {
    flex: 1;
  }
}

/* 自定义消息框样式 */
:deep(.confirm-delete) {
  background: #ef4444 !important;
  border-color: #ef4444 !important;
}
</style>
